package initial

import (
	"fmt"

	"gitee.com/y2h/beeqor/app"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"github.com/jinzhu/gorm"
	_ "github.com/lib/pq"
)

var DB *gorm.DB
var err error
var dblink string

func init() {
	initdb()

	app.QorAdmin(DB)
}

func initdb() {
	user := beego.AppConfig.DefaultString("db::user", "postgres")
	pwd := beego.AppConfig.DefaultString("db::pwd", "postgres")
	host := beego.AppConfig.DefaultString("db::host", "localhost")
	sslmode := beego.AppConfig.DefaultString("db::sslmode", "disable")
	port := beego.AppConfig.DefaultString("db::port", "5432")
	dbname := beego.AppConfig.DefaultString("db::dbname", "dvdrental")
	dbtype := beego.AppConfig.DefaultString("db::dbtype", "postgres")

	if beego.AppConfig.String("runmode") == "dev" {
		orm.Debug = true
	}
	if dbtype == "postgres" {
		orm.RegisterDriver("postgresql", orm.DRPostgres)
		dblink = fmt.Sprintf("user=%s password=%s dbname=%s host=%s port=%s sslmode=%s", user, pwd, dbname, host, port, sslmode)
		orm.RegisterDataBase("default", dbtype, dblink)
	}

	DB, err = gorm.Open("postgres", dblink)
	if err != nil {
		fmt.Println("can not open db, please verify your connection string")
	}
	// 全局禁用表名复数
	DB.SingularTable(true)
	// 启用Logger,显示详细日志
	DB.LogMode(true)
}
